﻿using System;
using System.Drawing;
using System.Resources;
using System.Windows.Forms;
using AiFrame.Base.Core.MVP;
using AiFrame.Base.Core.Plugins;
using AiFrame.Base.WinUI.MVP;
using AiFrame.InterfaceLib.MVP;
using AiFrame.InterfaceLib.Resources;
using AiFrame.InterfaceLib.Windows.Themes;

namespace AiFrame.Base.WinUI.Windows.UI
{
    public partial class MainWindowView : Form, IMainWindowView
    {
        private MainWindowPresenter _presenter;
        private Image _headerTitleImage;
        private Image _headerSpaceImage;
        private INavigationBar _navigationBar;
        private ResourceManager _resMan;
        private ITheme _theme;
        private IBaseFactory _baseFactory;

        public MainWindowView()
        {
            InitializeComponent();
            Width = 1120;
            Height = 700;
            _presenter = new MainWindowPresenter(this);
            _navigationBar = NavigationBarFactory.CreateNavigationBar();
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            this.Text = PluginManagerLoader.Instance().GetPluginManager().GetProductLine().ProgramName();

            _theme = PluginManagerLoader.Instance().
                GetPluginManager().GetApplicationTheme();
            ToolStripManager.Renderer = _theme.GetProfessionalColorTable();
            
            _resMan = new ResourceManager("OfficeProcessManager.Properties.Resources",
                this.GetType().Assembly);

            this.Icon = PluginManagerLoader.Instance().GetPluginManager().GetProductLine().Icon();

            if (_theme.GetMainHeaderImage() == null)
                headerPanel.Visible = false;
            else
            {
                _headerTitleImage = _theme.GetMainHeaderImage();   //(Image) _resMan.GetObject("header_logo");
                _headerSpaceImage = _theme.GetHeaderImageSpace();    
            }
            
            //headerPictureBox.Image = _theme.GetProgramHeader();

            /* Den Splitter erstellen */
            Splitter splitter = new Splitter();
            splitter.Parent = toolStripContainer1.ContentPanel;
            splitter.Dock = DockStyle.Left;
            
            /* Erst jetzt die NavigationBar auf die Form setzen, da
             * sonst der Splitter am linken Rand liegt. */
            _navigationBar.SetParent(toolStripContainer1.ContentPanel);
            _navigationBar.SetDockingStyle(DockStyle.Left);

            _presenter.Initialize();
        }

        /// <summary>
        /// Findet ein Control im einem Container.
        /// 
        /// Remember all controls (Panel, GroupBox, Form, etc are all 
        /// containsers for controls.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="name">Name des Controls, nach dem gesucht werden soll.</param>
        /// <returns></returns>
        private ToolStripMenuItem FindMenuControlRecursive(object container, string name)
        {

            /* Beim MenuStrip stehen die Controls unter Items... */
            if (container is MenuStrip)
            {
                MenuStrip menuStrip = (MenuStrip) container;
                foreach (ToolStripMenuItem item in menuStrip.Items)
                {
                    ToolStripMenuItem menuItem = FindMenuControlRecursive(item, name);
                    if (menuItem != null)
                        return menuItem;
                }
            }

            if (container is ToolStripMenuItem)
            {
                ToolStripMenuItem menuItem = (ToolStripMenuItem) container;

                if (menuItem.Name == name)
                    return menuItem;

                foreach (ToolStripDropDownItem dropDownItem in menuItem.DropDownItems)
                {
                    ToolStripMenuItem subMenuItem = FindMenuControlRecursive(container, name);
                    if (subMenuItem != null)
                        return subMenuItem;
                }
            }

            return null;
        }

        /// <summary>
        /// Fügt ein MenuItem ein.
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="name"></param>
        /// <param name="tooltip"></param>
        /// <param name="parentName"></param>
        /// <param name="clickProcedure"></param>
        /// <returns></returns>
        public object AddMainMenuItem(string caption, string name, string tooltip, string parentName, 
            OnMenuItemClickProcedure clickProcedure)
        {
            ToolStripDropDownItem menuItem = new ToolStripMenuItem(caption);
            menuItem.ToolTipText = tooltip;

            /* Nur eintragen, wenn die Prozedur nicht NULL ist. */
            if (clickProcedure != null)
                menuItem.Click += new EventHandler(clickProcedure);

            /* Das Parent-Item suchen, unter dem das aktuelle Item
             * eingefügt werden soll */
            ToolStripMenuItem parentItem = FindMenuControlRecursive(this.menuStrip1, parentName);
            
            if (parentItem == null)
                throw new MenuItemException(string.Format("Das Menuitem mit dem Namen {0} konnte nicht gefunden werden", name));

            parentItem.DropDownItems.Insert(0, menuItem);
            
            return menuItem;
        }

        public object AddMainMenuItem(string caption, string name, string tooltip, object parent, OnMenuItemClickProcedure clickProcedure, object shortCutKeys)
        {
            ToolStripMenuItem menuItem = new ToolStripMenuItem(caption);
            menuItem.ToolTipText = tooltip;

            /* Nur eintragen, wenn die Prozedur nicht NULL ist. */
            if (clickProcedure != null)
                menuItem.Click += new EventHandler(clickProcedure);

            if (parent == null)
            {
                menuStrip1.Items.Add(menuItem);
            }
            else
            {
                /* Das Parent-Item suchen, unter dem das aktuelle Item
                 * eingefügt werden soll */
                ToolStripMenuItem parentItem = (ToolStripMenuItem)parent;

                if (parentItem == null)
                    throw new MenuItemException(string.Format("Das übergebene MenuItem ist kein gültiges ToolStripMenuItem", name));

                parentItem.DropDownItems.Add(menuItem); //Insert(0, menuItem);
                if (shortCutKeys != null)
                {
                    if (!(shortCutKeys is Keys))
                        throw new MenuItemException(string.Format("Das MenuItem {0} enthält ungültige Shortcuts", caption));

                    menuItem.ShortcutKeys = (Keys) shortCutKeys;
                }
            }

            return menuItem;
        }

        public object AddMainMenuItem(string caption, string name, string tooltip, object parent, OnMenuItemClickProcedure clickProcedure)
        {
            return AddMainMenuItem(caption, name, tooltip, parent, clickProcedure, null);
        }

        /// <summary>
        /// Entfernt ein MenuItem.
        /// </summary>
        /// <param name="menuItem"></param>
        public void RemoveMainMenuItem(object menuItem)
        {
            if (!(menuItem is ToolStripMenuItem))
                throw new MenuItemException("Das MenuItem konnte nicht gelöscht werden, da es kein ToolStripItem ist.");

            ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem)menuItem;

            //ToolStripMenuItem e = FindMenuControlRecursive(this.menuStrip1, StringEnum.GetStringValue(MainMenuItems.FileMenu));
            //Console.WriteLine(e.DropDownItems.Count);

            /* Durch das Dispose wird das Element automatisch ausgetragen aus der Liste
             * und freigegeben. */
            toolStripMenuItem.Dispose();
            toolStripMenuItem = null;
            
            //Console.WriteLine(e.DropDownItems.Count);
        }

        private void headerPanel_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImage(_theme.GetProgramHeader(), 0, 0, _theme.GetProgramHeader().Width, 55);
            e.Graphics.DrawImage(_headerSpaceImage, _theme.GetProgramHeader().Width , 0, Width, 55);

            e.Graphics.DrawImage(_headerTitleImage, 15, 15, _headerTitleImage.Width,
                _headerTitleImage.Height);
        }

        public void RegisterMainToolPanel()
        {
            /* Images laden */
            ResourceImages resourceImages = new ResourceImages();
            ToolStrip ts = new ToolStrip();


            ToolStripButton copyButton = new ToolStripButton("", resourceImages.Copy, OnToolClick);
            copyButton.Tag = "Copy";
            ts.Items.Add(copyButton);

            ToolStripButton cutButton = new ToolStripButton("", resourceImages.Cut, OnToolClick);
            cutButton.Tag = "Cut";
            ts.Items.Add(cutButton);

            ToolStripButton pasteButton = new ToolStripButton("", resourceImages.Paste, OnToolClick);
            pasteButton.Tag = "Copy";
            ts.Items.Add(pasteButton);

            /* Als dauerhaftes Element registrieren */
//            ToolBarManager.Instance.AddToolGroup(ts, true);
        }

        private void OnToolClick(object sender, EventArgs e)
        {
//            if (sender == aktualisierenToolStripMenuItem)
//                TabSetManager.Instance().RefreshView();
        }

        public Control GetContentPanel()
        {
            return toolStripContainer1.ContentPanel;
        }

        public Control GetWindowCaptionControl()
        {
            throw new System.NotImplementedException();
        }

        public void ClearContainers()
        {
            throw new System.NotImplementedException();
//            _tabControl.TabPages.Clear();
        }

        public ToolStripPanel ToolPanel
        {
            get
            {
                return toolStripContainer1.TopToolStripPanel;
            }
        }

        public void AddContainer(IWindow wnd)
        {
            wnd.SetParentWindow(dockPanel);
        }

        public INavigationBar GetNavBar()
        {
            return _navigationBar;
        }

        public void SetOnlineStatusText(string message)
        {
            toolStripStatusLabel1.Text = message;
        }

        public void SetStatusText(string message)
        {
            toolStripStatusLabel2.Text = message;
        }

        private void MainWindowView_SizeChanged(object sender, EventArgs e)
        {
            //Text = Width + " * " + Height;
            //toolStripStatusLabel2.Width = Width - 330;
        }

        public IBaseFactory BaseFactory
        { 
            set
            {
                _baseFactory = value;
//                _presenter.InitializeBaseFactory(value);
            }
        }

        private void beendenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _presenter.UserWantsToClose();
        }

    }
}